define


The Pre-Processor

The pre-processor is a part of the compiler that can make basic text operations. These operations are performed before generating the the final code and are extremely useful.
El pre-procesador es parte del compilador que puede hacer manipulaciones de texto básicas. Estas manipulaciones se realizan antes de generar el código final y son extremadamente útiles.

#define

In some cases, a program requires to write some text in several parts of it. C++ provides the pre-processor instruction #define to define some text that can be easily updated eliminating possible errors. #define is used to defined an identifier and a sequence of characters that will be substitute by the identifier each time it is found in the source code. This type of function ability is known as macros. In the example shown below, the instruction #define was used to define INCHES as a value of 12; the pre-processor will replace all occurrences of INCHES with the value of 12 before compiling the program.
En algunos casos, un programa requiere que se escriba cierto texto en diversas partes de él. C++ tiene la instrucción del pre-procesador #define para definir un texto que puede ser fácilmente modificado eliminándose algunos errores posibles. #define es un usado para definir un identificador y una secuencia de caracteres que serán sustituidos por el identificador cada vez que éste sea encontrado en el código fuente. Este tipo de funcionalidad se conoce como macros. En el ejemplo mostrado debajo, la instrucción #define fue usada para definir INCHES como un valor de 12; el pre-procesador reemplazará todas las ocurrencias de INCHES con el valor de 12 antes de compilar el programa.

define

Tip
It is good programming technique to use uppercase characters to define the macros with #define. It is also recommended to place all the macros at the beginning of the header file. It is also a good programming technique to use uppercase characters to define the identifier of a #define. In the code shown below, the BLOCK_WIDTH macro was defined as 100. Thus, the pre-processor will replace all occurrences of BLOCK_WIDTH with the text 100 in any part of the code.
Es de buena práctica usar letras mayúsculas para los macros definidos con #define. Es bueno también colocar todas estas definiciones al principio de un archivo de encabezado. Es de buena práctica usar letras mayúsculas para los macros definidos con #define. En el código mostrado debajo, el macho BLOCK_WIDTH fue definido como 100. Así, el pre-procesador reemplazará todas las ocurrencias de BLOCK_WITH con el texto 100 en cualquier parte del código.

Program.h
#define BLOCK_WIDTH 100

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     double area = BLOCK_WIDH*BLOCK_WIDTH;
}


Tip
Several common values in Math and Programming are defined using #define. For instance, M_PI has a value of 3.14159265358979323846, M_E has value of 2.71828182845904523536. When the mouse is places over any macro, Microsoft Visual Studio shows the expansion of the macro. It is also possible to navigate to the definition of the macro using the context menu (right mouse click) and selecting the option: Go to Definition.
Varios valores comunes de Matemáticas y Programación están definidos usando #define. Por ejemplo, M_PI tiene un valor de 3.14159265358979323846, M_E tiene un valor de 2.71828182845904523536. Cuando el ratón se coloca encima de un macro, Microsoft Visual Studio muestra la expansión del macro. Es posible navegar a la definición del macro usando el menú de contexto (usando el botón derecho del ratón) y seleccionando la opción: Ir a la Definición.

M_PI

Tip
JavaIn Java, Math constants are defined in Math, for instance: Math.PI, and Math.E.
JavaEn Java, las constantes de Matemáticas están definidas en Math, por ejemplo: Math.PI, y Math.E.

Tip
In C#, Math constants are defined in Math, for instance: Math.PI, and Math.E.
En C# las constantes de Matemáticas están definidas en Math, por ejemplo: Math.PI y Math.E.

Problem 1
Write a program called Circulo to calculate the area and perimeter of a circle using the constant M_PI defined in the C++ language.
Escriba un programa llamado Circulo para calcular el área y el perímetro del circulo usando la constante M_PI definida en el lenguaje C++.

Circulo

Tip
When the user click a button in a Message Box, the box closes and returns and integer value that indicates what button the user pressed. The possible values are: IDABORT, IDCANCEL, IDCONTINUE, IDIGNORE, IDNO, IDOK, IDRETRY, IDTRYAGAIN, IDYES.
Cuando el usuario hace clic en algún botón de la caja de mensajes, la caja se cierra y regresa un valor entero para indicar que botón fue presionado por el usuario. Los valores posibles son: IDABORT, IDCANCEL, IDCONTINUE, IDIGNORE, IDNO, IDOK, IDRETRY, IDTRYAGAIN, IDYES.

Problem 2
Create a project called Question using Wintempla and write the code shown below.
Cree un proyecto llamado Question usando Wintempla y escriba el código mostrado debajo.

Question

Tip
In the previous problem, the program opens a Message Box. The sentence if is used to check what button the user pressed. When the user clicks the Yes button, the message box returns a value of IDYES (which Microsoft Window defines as 6 in the file WinUser.h which is included in the file Windows.h included in all Wintempla projects). Thus, the program executes the line
this->Text = L"Yes!";
only when the user presses the Yes button. In other words, the text that is displayed at the top of the main window will change only when the user presses the Yes button in the message box.
En el problema anterior, el programa abre una caja de mensajes. El comando if es usando para verificar que botón fue presionado por el usuario. Cuando el usuario hace clic en el botón de Sí, la caja de mensaje regresa un valor de IDYES (el cual está definido como 6 en el archivo WinUser.h el cual se incluye en el archivo Windows.h incluído en todos los proyectos de Wintempla). Así, el programa ejecuta la línea
this->Text = L"Yes!";
solamente cuando el usuario presiona el botón de Sí. En otras palabras, el texto que es mostrado en la parte superior de la ventana principal cambiará solamente cuando el usuario presione el botón de Sí.

Problem 3
Write a program called Circle to compute the area and perimeter of a circle; when the user presses the Calculate button the program asks the user if he wants to use inches for the calculations. If the user answers Yes, the program will display the results with the respective units (squared inches and inches). If the user answers No, the program will display the results with the respective units (squared cm and cm). Remember that a MessageBox returns an integer value (IDOK, IDCANCEL, IDABORT, IDRETRY, IDIGNORE, IDYES, IDNO, IDCLOSE, IDHELP, IDTRYAGAIN, IDCONTINUE).
Escriba un programa llamado Circle para calcular el área y el perímetro de un círculo; cuando el usuario presiona el botón de Calculate el programa pregunta si él quiere usar pulgadas para los cálculos. Si el usuario contesta Si, el programa mostrará los resultados con las respectivas unidades (pulgadas cuadrada y pulgadas). Si el usuario contesta No, el programa mostrará los resultados con las respectivas unidades (centímetros cuadrados y centímetros). Recuerde que una Caja de Mensaje regresa un valor entero (IDOK, IDCANCEL, IDABORT, IDRETRY, IDIGNORE, IDYES, IDNO, IDCLOSE, IDHELP, IDTRYAGAIN, IDCONTINUE).

CircleQuestion

CircleIn

CircleCm

Problem 4
Repeat the previous problem using Win32.
Repita el problema anterior usando Win32.

Circle32.cpp
//_________________________________________________ Circle32.cpp
#include "stdafx.h"
#include "Circle32.h"

#define _USE_MATH_DEFINES 1
#include <math.h>

INT_PTR Window_Open(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
     ::SetWindowText(hWnd, L"Circle32");
     return TRUE;
}

INT_PTR btCalculate_Click(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
     const int answer = ::MessageBox(NULL, L"Do you want to use inches?", L"Circle32", MB_YESNO | MB_ICONQUESTION);
     wchar_t text[32];
     //_______________________________ Extract Radius
     ::GetWindowText(::GetDlgItem(hWnd, ID_TBX_RADIUS), text, 32);
     const double radius = _wtof(text);
     //_______________________________ Calculations
     const double area = M_PI*radius*radius;
     const double perimeter = 2.0*M_PI*radius;
     //_______________________________ Display the area
     _snwprintf_s(text, 32, _TRUNCATE, L"%f",area);
     ::SetWindowText(::GetDlgItem(hWnd, ID_TBX_AREA), text);
     //_______________________________ Display the perimeter
     _snwprintf_s(text, 32, _TRUNCATE, L"%f", perimeter);
     ::SetWindowText(::GetDlgItem(hWnd, ID_TBX_PERIMETER), text);
     //
     if (answer == IDYES)
     {
          ::SetWindowText(::GetDlgItem(hWnd, ID_LB_AREA), L"sq_in");
          ::SetWindowText(::GetDlgItem(hWnd, ID_LB_PERIMETER), L"in");
     }
     else
     {
          ::SetWindowText(::GetDlgItem(hWnd, ID_LB_AREA), L"sq_cm");
          ::SetWindowText(::GetDlgItem(hWnd, ID_LB_PERIMETER), L"cm");
     }
     return TRUE;
}

INT_PTR CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     switch (message)
     {
     case WM_INITDIALOG:
          return Window_Open(hWnd, wParam, lParam);
     case WM_COMMAND:
          if (LOWORD(wParam) == ID_BT_CALCULATE) return btCalculate_Click(hWnd, wParam, lParam);
          if (LOWORD(wParam) == IDCANCEL) ::EndDialog(hWnd, 0);
          break;
     }
     return (INT_PTR)FALSE;
}

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR cmdLine, int cmdShow)
{
     ::DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, WndProc);
     return 0;
}


Problem 5
Repeat the previous problem using C#, called your proyect CircleS.
Repita el problema anterior usando C#, llame a su proyecto CircleS.

CircleSRun

Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CircleS
{
     public partial class Form1 : Form
     {
          public Form1()
          {
               InitializeComponent();
          }

          private void Calculate_Click(object sender, EventArgs e)
          {
               DialogResult answer = MessageBox.Show("Do you want to use inches?", "Circle32", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
               double radius = ...;
               //_______________________________ Calculations
               ...
               //_______________________________ Display the area
               ...
               //_______________________________ Display the perimeter
               ...
               //
               if (answer == DialogResult.Yes)
               {
                    ...
               }
               else
               {
                    ...
               }
          }
     }
}


Problem 6
Indicate whether the following statement is true or false: Macros can be used to facilitate the update of one value that is used in several parts of a program; this value may change in future versions during the life cycle of the program.
Indique si la siguiente sentencia es verdadera o falsa: Los macros pueden ser usados para facilitar la actualización de un valor que es usado en varias partes de un programa; este valor puede cambiar en versiones futuras durante el ciclo de vida del programa.

Tip
javaJava does not support the #define command. Only C and C++ support the #define command.
Java no suporta el comando #define. Solamente C y C++ soportan el comando #define.

Tip
In Java and C# it is possible to use a static member function that returns a value, and provide a similar functionability to #define.
En Java y C# es posible usar una función estática miembro para regresar un valor, y proporcionar una funcionalidad similar a #define.

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home